<script setup lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import { try_post_book, ImportOptions,try_parse_books_from_excel, try_post_books } from "./book";
import { UseLibraryState } from "../library_state";
import type { FormInstance, FormRules } from "element-plus";
import { NewBook } from "./book";
import { ElNotification } from "element-plus";

const form_ref = ref<FormInstance>();

const import_options: Partial<ImportOptions> = reactive({
  skipHeader: true,
  bookNameCol: undefined,
  authorCol: undefined,
  publisherCol: undefined,
  indexNoCol: undefined,
  totalCountCol: undefined,
  availableCountCol: undefined,
  file: undefined,
});

const validate_col_name = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback();
  } else if (/[^a-z]/i.test(value)) {
    callback(new Error("列名必须是A-Z的字母!"));
  } else {
    callback();
  }
};
const validate_file=(rule: any, value: any, callback: any)=>{
  if (!import_options.file) {
    callback(new Error('没有选择文件!'))
  }else{
    callback()
  }
}
const rules = reactive<FormRules>({
  file:[{validator:validate_file}],
  bookNameCol: [
    { required: true, type: "string", message: "书籍名不得为空!" },
    { validator: validate_col_name },
  ],
  authorCol: [{ validator: validate_col_name }],
  publisherCol: [{ validator: validate_col_name }],
  indexNoCol: [{ validator: validate_col_name }],
  totalCountCol: [
    { required: true, type: "string",message: "书籍总量不得为空!" },
  ],
  availableCountCol: [
    { required: true, type: "string", message: "可借数量不得为空!" },
  ],
});

const reset_form = () => {
  if (!form_ref.value) {
    return;
  }
  form_ref.value.resetFields();
};
const parsed_books=ref<NewBook[]>([])
const submit = async () => {
  if (!form_ref.value) {
    return;
  }
  const is_ok = await form_ref.value.validate();
  if (!is_ok) {
    return
  }
    try {
    parsed_books.value=await try_parse_books_from_excel(import_options)
  } catch (error) {
    ElNotification.error({
        message: "解析文件失败!\n" + error,
        duration:10000,
        title:'Error'
    })
    return
  }
  show_dialog.value=true
};

const book_samples=computed(() => {
  return parsed_books.value.slice(0,5)
})

const show_dialog=ref(false)

const confirm_import=async ()=>{
  try {
    const result=await try_post_books(parsed_books.value)
    let ok_msg=`导入书籍成功!\n`
    ok_msg+=`总共上传:${result.acceptCount}\n`
    ok_msg+=`成功导入:${result.importCount}\n`
    ok_msg+=`去除重复:${result.repeatCount}\n`
    ElNotification.success({
      message:ok_msg,
      title:'Success',
      duration:5000,
    })
    show_dialog.value=false
  } catch (error) {
    ElNotification.error({
      message:'导入书籍失败!\n'+error,
      title:'Error',
      duration:10000,
    })
  }
}
</script>

<template>
  <el-form
    label-position="right"
    label-width="140px"
    style="max-width: 460px"
    ref="form_ref"
    status-icon
    :model="import_options"
    :rules="rules"
  >
    <el-form-item label="Excel文件" prop="file">
      <input
        type="file"
        required
        accept=".xls,.xlsx"
        @change="import_options.file=($event.target! as HTMLInputElement).files![0]"
      />
    </el-form-item>
    <el-form-item label="跳过标题行" prop="skipHeader">
      <el-switch v-model="import_options.skipHeader" />
    </el-form-item>
    <el-form-item label="书名所在列" prop="bookNameCol">
      <el-input v-model="import_options.bookNameCol" />
    </el-form-item>
    <el-form-item label="作者所在列" prop="authorCol">
      <el-input v-model="import_options.authorCol" />
    </el-form-item>
    <el-form-item label="出版社所在列" prop="publisherCol">
      <el-input v-model="import_options.publisherCol" />
    </el-form-item>
    <el-form-item label="索引号所在列" prop="indexNoCol">
      <el-input v-model="import_options.indexNoCol" />
    </el-form-item>
    <el-form-item label="入库数量所在列" prop="totalCountCol">
      <el-input v-model="import_options.totalCountCol" />
    </el-form-item>
    <el-form-item label="可借数量所在列" prop="availableCountCol">
      <el-input v-model="import_options.availableCountCol" />
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="reset_form()">重置</el-button>
      <el-button type="primary" @click="submit()">确认</el-button>
    </el-form-item>
  </el-form>
  <el-dialog 
  v-model="show_dialog" 
  title="解析结果"
  width="80%"
  >
    <p>{{`总计${parsed_books.length}本, 展示若干本`}}</p>
    <el-table :data="book_samples">
      <el-table-column type="index" width="60" label="No"/>
      <el-table-column property="bookName" label="书名" />
      <el-table-column property="author" label="作者" width="200" />
      <el-table-column property="publisher" label="出版商" width="200" />
      <el-table-column property="indexNo" label="索引号" width="100" />
      <el-table-column property="totalCount" label="总量" width="100" />
      <el-table-column property="availableCount" label="可借数量" width="100" />
    </el-table>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="show_dialog = false">取消</el-button>
        <el-button type="primary" @click="confirm_import()"
          >上传</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
